//
//  Weixin.m
//  Running
//
//  Created by 郑东喜 on 2016/10/30.
//  Copyright © 2016年 郑东喜. All rights reserved.
//

#import "Weixin.h"


static NSString *kLinkURL = @"http://dog.ie1e.com:8081";
static NSString *kLinkTagName = @"WECHAT_TAG_JUMP_SHOWRANK";
static NSString *kLinkTitle = @"暴走狗";


//授权登陆
//微信
static NSString * const kWX_AppId =         @"wxd6870b76bf49dd4c";
static NSString * const kWX_AppSecret =     @"8765965abd382bd6216b230b11bc3bb1";

// 授权域：通俗讲就是接口的使用权限
static NSString *kAuthScope  = @"snsapi_message,snsapi_userinfo,snsapi_friend,snsapi_contact";
//static NSString *kAuthOpenID = @"0c806938e2413ce73eef92cc3";
static NSString *kAuthState  = @"xxx";

//#define WXPatient_App_ID @"wxd6870b76bf49dd4c"
//#define WXPatient_App_Secret @"8765965abd382bd6216b230b11bc3bb1"
#define WX_ACCESS_TOKEN @"access_token"
#define WX_OPEN_ID @"openid"
#define WX_REFRESH_TOKEN @"refresh_token"
#define WX_UNION_ID @"unionid"
#define WX_BASE_URL @"https://api.weixin.qq.com/sns"


@implementation Weixin


//.m
+(Weixin *)shareDataSource {
    static Weixin *dataSource = nil;
    static dispatch_once_t once;
    dispatch_once(&once,^{
        dataSource = [Weixin new];
    });
    return dataSource;
    
}

- (AFHTTPSessionManager *)manager {
    if (!_manager) {
        _manager = [[AFHTTPSessionManager alloc] init];
    }
    return _manager;
}

- (void)onReq:(BaseReq *)req {
    NSLog(@"%s  %d  ",__func__,__LINE__);
}

+ (void)weixinShareWithDescription:(NSString *)desc {
    //创建发送对象实例
    SendMessageToWXReq *sendReq = [[SendMessageToWXReq alloc] init];
    sendReq.bText = NO;//不使用文本信息
    sendReq.scene = 1;//0 = 好友列表 1 = 朋友圈 2 = 收藏
    
    //创建分享内容对象
    WXMediaMessage *urlMessage = [WXMediaMessage message];
    urlMessage.title = kLinkTitle;//分享标题
    urlMessage.description = desc;//分享描述
    
    
    [urlMessage setThumbImage:[UIImage imageNamed:@"ic_launcher"]];//分享图片,使用SDK的setThumbImage方法可压缩图片大小
    
    //创建多媒体对象
    WXWebpageObject *webObj = [WXWebpageObject object];
    webObj.webpageUrl = kLinkURL;//分享链接
    
    //完成发送对象实例
    urlMessage.mediaObject = webObj;
    sendReq.message = urlMessage;
    
    //发送分享信息
    [WXApi sendReq:sendReq];
}

+ (void)weixinPay {
    NSString *res = [self jumpToBizPay];
    if( ![@"" isEqual:res] ){
        UIAlertView *alter = [[UIAlertView alloc] initWithTitle:@"支付失败" message:res delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
        
        [alter show];
        
    }
    
}

+ (NSString *)jumpToBizPay {
    
    //============================================================
    // V3&V4支付流程实现
    // 注意:参数配置请查看服务器端Demo
    // 更新时间：2015年11月20日
    //============================================================
    NSString *urlString   = @"http://wxpay.weixin.qq.com/pub_v2/app/app_pay.php?plat=ios";
    //解析服务端返回json数据
    NSError *error;
    //加载一个NSURL对象
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
    //将请求的url数据放到NSData对象中
    NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    if ( response != nil) {
        NSMutableDictionary *dict = NULL;
        //IOS5自带解析类NSJSONSerialization从response中解析出数据放到字典中
        dict = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:&error];
        
        NSLog(@"url:%@",urlString);
        if(dict != nil){
            NSMutableString *retcode = [dict objectForKey:@"retcode"];
            if (retcode.intValue == 0){
                NSMutableString *stamp  = [dict objectForKey:@"timestamp"];
                
                //调起微信支付
                PayReq* req             = [[PayReq alloc] init];
                req.partnerId           = [dict objectForKey:@"partnerid"];
                req.prepayId            = [dict objectForKey:@"prepayid"];
                req.nonceStr            = [dict objectForKey:@"noncestr"];
                req.timeStamp           = stamp.intValue;
                req.package             = [dict objectForKey:@"package"];
                req.sign                = [dict objectForKey:@"sign"];
                [WXApi sendReq:req];
                //日志输出
                NSLog(@"appid=%@\npartid=%@\nprepayid=%@\nnoncestr=%@\ntimestamp=%ld\npackage=%@\nsign=%@",[dict objectForKey:@"appid"],req.partnerId,req.prepayId,req.nonceStr,(long)req.timeStamp,req.package,req.sign );
                return @"";
            }else{
                return [dict objectForKey:@"retmsg"];
            }
        }else{
            return @"服务器返回错误，未获取到json对象";
        }
    }else{
        return @"服务器返回错误";
    }
}

//微信授权登陆
-(void)clickAuthButton {
    NSString *accessToken = [[NSUserDefaults standardUserDefaults] objectForKey:WX_ACCESS_TOKEN];
    NSString *openID = [[NSUserDefaults standardUserDefaults] objectForKey:WX_OPEN_ID];
    // 如果已经请求过微信授权登录，那么考虑用已经得到的access_token
    if (accessToken && openID) {
        
        NSString *refreshToken = [[NSUserDefaults standardUserDefaults] objectForKey:WX_REFRESH_TOKEN];
        NSString *refreshUrlStr = [NSString stringWithFormat:@"%@/oauth2/refresh_token?appid=%@&grant_type=refresh_token&refresh_token=%@", WX_BASE_URL, kWX_AppId, refreshToken];
        
        [self.manager GET:refreshUrlStr parameters:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSDictionary *refreshDict = [NSDictionary dictionaryWithDictionary:responseObject];
            NSString *reAccessToken = [refreshDict objectForKey:WX_ACCESS_TOKEN];
            
            NSLog(@"%s  %d  %@",__func__,__LINE__,reAccessToken);
            // 如果reAccessToken为空,说明reAccessToken也过期了,反之则没有过期
            if (reAccessToken) {
                // 更新access_token、refresh_token、open_id
                [[NSUserDefaults standardUserDefaults] setObject:reAccessToken forKey:WX_ACCESS_TOKEN];
                [[NSUserDefaults standardUserDefaults] setObject:[refreshDict objectForKey:WX_OPEN_ID] forKey:WX_OPEN_ID];
                [[NSUserDefaults standardUserDefaults] setObject:[refreshDict objectForKey:WX_REFRESH_TOKEN] forKey:WX_REFRESH_TOKEN];
                [[NSUserDefaults standardUserDefaults] synchronize];
                // 当存在reAccessToken不为空时直接执行AppDelegate中的wechatLoginByRequestForUserInfo方法
                !self.requestForUserInfoBlock ? : self.requestForUserInfoBlock();
            }
            else {
                [self wechatLogin];
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"用refresh_token来更新accessToken时出错 = %@", error);
        }];
    }
    else {
        [self wechatLogin];
    }
    
}

- (void)wechatLogin {
    if ([WXApi isWXAppInstalled]) {
        SendAuthReq *req = [[SendAuthReq alloc] init];
        req.scope = @"snsapi_userinfo";
        req.state = @"GSTDoctorApp";
        [WXApi sendReq:req];
    }
    else {
        [self setupAlertController];
    }
    
}

#pragma mark - 设置弹出提示语
- (void)setupAlertController {
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"请先安装微信客户端" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *actionConfirm = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
    [alert addAction:actionConfirm];
    [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alert animated:YES completion:nil];
}


// 授权后回调
// AppDelegate.m
- (void)onResp:(BaseResp *)resp {
    
    
    //分享
    if ([resp isKindOfClass:[SendMessageToWXResp class]]) {
        switch (resp.errCode) {
            case 0: {
                NSLog(@"%s  %d  %@",__func__,__LINE__,@"分享成功");
                
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"分享成功" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                [alert show];}
                break;
                
            default:
                NSLog(@"%s  %d  %@",__func__,__LINE__,@"分享黑白");
                
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"分享失败" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                [alert show];
                break;
        }
    }
    
    //支付
    if ([resp isKindOfClass:[PayResp class]]) {
        switch (resp.errCode) {
            case 0: {
                NSLog(@"%s  %d  %@",__func__,__LINE__,@"支付成功");
                
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"支付成功" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                [alert show];}
                break;
                
            default:
                NSLog(@"%s  %d  %@",__func__,__LINE__,@"支付失败");
                
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"支付失败" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                [alert show];
                break;
        }
    }
    
    
    NSLog(@"%s  %d  ",__func__,__LINE__);
    // 向微信请求授权后,得到响应结果
    if ([resp isKindOfClass:[SendAuthResp class]]) {
        SendAuthResp *temp = (SendAuthResp *)resp;
        
        NSLog(@"%s  %d  %zd",__func__,__LINE__,temp.errCode);
        
        NSString *accessUrlStr = [NSString stringWithFormat:@"%@/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code", WX_BASE_URL, kWX_AppId, kWX_AppSecret, temp.code];
        
        switch (temp.errCode) {
            case 0:{
                [self.manager GET:accessUrlStr parameters:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                    
                    
                    NSLog(@"请求access的response = %@", responseObject);
                    NSDictionary *accessDict = [NSDictionary dictionaryWithDictionary:responseObject];
                    NSString *accessToken = [accessDict objectForKey:WX_ACCESS_TOKEN];
                    NSString *openID = [accessDict objectForKey:WX_OPEN_ID];
                    NSString *refreshToken = [accessDict objectForKey:WX_REFRESH_TOKEN];
                    // 本地持久化，以便access_token的使用、刷新或者持续
                    if (accessToken && ![accessToken isEqualToString:@""] && openID && ![openID isEqualToString:@""]) {
                        [[NSUserDefaults standardUserDefaults] setObject:accessToken forKey:WX_ACCESS_TOKEN];
                        [[NSUserDefaults standardUserDefaults] setObject:openID forKey:WX_OPEN_ID];
                        [[NSUserDefaults standardUserDefaults] setObject:refreshToken forKey:WX_REFRESH_TOKEN];
                        [[NSUserDefaults standardUserDefaults] synchronize]; // 命令直接同步到文件里，来避免数据的丢失
                    }
                    [self wechatLoginByRequestForUserInfo];
                    
                    NSLog(@"%s  %d  %@",__func__,__LINE__,@"授权成功");
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"授权成功" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                    [alert show];
                    
                } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                    NSLog(@"获取access_token时出错 = %@", error);
                }];
            }
                
                break;
                
            default:
                NSLog(@"%s  %d  %@",__func__,__LINE__,@"授权失败");
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"授权失败" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                [alert show];
                break;
        }
        
            }
}

// AppDelegate.m
// 获取用户个人信息（UnionID机制）
- (void)wechatLoginByRequestForUserInfo {
    
    NSLog(@"%s  %d  ",__func__,__LINE__);
    NSString *accessToken = [[NSUserDefaults standardUserDefaults] objectForKey:WX_ACCESS_TOKEN];
    NSString *openID = [[NSUserDefaults standardUserDefaults] objectForKey:WX_OPEN_ID];
    NSString *userUrlStr = [NSString stringWithFormat:@"%@/userinfo?access_token=%@&openid=%@", WX_BASE_URL, accessToken, openID];
    
    [self.manager GET:userUrlStr parameters:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)  {
        
        NSLog(@"%s  %d 请求用户信息的response =  %@",__func__,__LINE__,responseObject);
        
        
        NSLog(@"%s  %d  %@",__func__,__LINE__,@"登陆成功");
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"获取用户信息时出错 = %@", error);
        NSLog(@"%s  %d  %@",__func__,__LINE__,@"登陆失败");
        
    }];
}




@end
